//
//  GYPNetworking.m
//  AmountBody
//
//  Created by smm on 17/12/6.
//  Copyright © 2017年 RCMTM. All rights reserved.
//

#import "GYPNetworking.h"
#import <objc/runtime.h>
//#import "ImageModel.h"
//#import "VideoModel.h"

@implementation GYPNetworking

#pragma mark - 解析生成post参数
+(NSDictionary *)parameterDictionaryWithUrlString:(NSString *)urlStr
{
    if (!urlStr || ![urlStr isKindOfClass:[NSString class]]) {
        return nil;
    }
    
    NSArray *tmpAndArray = [urlStr componentsSeparatedByString:@"&"];
    NSMutableDictionary *tmpDic = [[NSMutableDictionary alloc] init];
    for (NSString *tmpString in tmpAndArray) {
        if (![tmpString isKindOfClass:[NSString class]]) {
            continue;
        }
        
        NSArray *tmpEqualArray = [tmpString componentsSeparatedByString:@"="];
        if (tmpEqualArray.count == 2) {
            NSString *tmpKey = [NSString stringWithFormat:@"%@", tmpEqualArray[0]];
            NSString *tmpValue = [NSString stringWithFormat:@"%@", tmpEqualArray[1]];
            //如果登录的key不存在或者为空，则认为不需要做网络请求
            if ([tmpKey isEqualToString:@"key"] && [tmpValue isEqualToString:@""]) {
                return nil;
            }
            
            [tmpDic setValue:tmpValue forKey:tmpKey];
        }
        
    }
    return tmpDic;
}

+(id)netWorkingPOSTWithParameters:(NSString *)parameters andPost:(NSString *)postStr andSuccess:(void (^)(id, id, bool))success andFailure:(void (^)(NSError *))failure
{
    [GlobalFunction shownetActivityindicator];
    AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];
    sessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];
    //获取参数字典
    NSDictionary *params = [self parameterDictionaryWithUrlString:parameters];
    //执行网络请求
    id networkOperation = [sessionManager POST:postStr parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [GlobalFunction hidenetActivityindicator];
        NSDictionary *rootDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        if (!rootDic || ![rootDic isKindOfClass:[NSDictionary class]]) {
            NSError * error = [[NSError alloc] initWithDomain:@"datasError" code:0 userInfo:@{NSLocalizedDescriptionKey:@"网络请求返回值有误!"}];
            failure(error);
            return;
        }
        id datasValue;
        BOOL hasmore = NO;
        if ([rootDic.allKeys containsObject:@"data"]) {
            datasValue = [rootDic objectForKey:@"data"];
            //登录异常相关
            if ([datasValue isKindOfClass:[NSDictionary class]]) {
                hasmore = [GlobalHandleValue([datasValue valueForKey:@"has_more"]) boolValue]; 
                NSString *tmpLoginValue = GlobalHandleValue([datasValue valueForKey:@"msg"]);
                if ([tmpLoginValue isEqualToString:@"key值错误！"]) {
                    NSError *error = [[NSError alloc] initWithDomain:@"datasError" code:1 userInfo:@{NSLocalizedDescriptionKey:@"会员登录异常!"}];
                    
                    failure(error);
                    
                    //发送登录异常的通知
                    if ([UserManager isLogin]) {
                        //登录异常处理
                        [UserManager logoff];
                        [[NSNotificationCenter defaultCenter] postNotificationName:@"LoginAbnormal" object:nil];
                    }
                    return;
                }
            }
           
        }
        
        
        
        success(rootDic,datasValue,hasmore);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [GlobalFunction hidenetActivityindicator];
        failure(error);
    }];
    
    return networkOperation;
}



#pragma mark - 依据数组生成model
//生成Model数据类型的类，以存放数据
+(NSArray *)createArrayFromArray:(NSArray *)tmpArray andClassName:(NSString *)className andPropertyArray:(NSArray *)propertyArray andKeysArray:(NSArray *)keysArray
{
    if (!tmpArray || ![tmpArray isKindOfClass:[NSArray class]]) {
        return nil;
    }
    
    NSMutableArray *resArray = [[NSMutableArray alloc] init];
    //解析相关的数据结构。。。
    //获取相关数据类型
    const char *cClassName = [className UTF8String];
    
    id theClass = objc_getClass(cClassName);
    
    //如果提供的Model属性组成的数组不存在，则根据数据类型生成关键字数组
    if (!propertyArray || [propertyArray count] == 0) {
        unsigned int outCount;
        
        objc_property_t *properties = class_copyPropertyList(theClass, &outCount);
        
        NSMutableArray *propertyNames = [[NSMutableArray alloc] initWithCapacity:1];
        
        for (int i = 0; i < outCount; i++) {
            
            objc_property_t property = properties[i];
            
            NSString *propertyNameString = [[NSString alloc] initWithCString:property_getName(property) encoding:NSUTF8StringEncoding];
            
            [propertyNames addObject:propertyNameString];
            
        }
        propertyArray = propertyNames;
    }
    
    //需要解析的对应返回的数据结构里面的key的关键字
    if (!keysArray || [keysArray count] == 0) {
        keysArray = propertyArray;
    }
    if (keysArray.count != propertyArray.count) {
        NSLog(@"两个数组不对等");
        return nil;
    }
    
    //循环取解析出来的数据并赋值
    for (NSDictionary *tmpDic in tmpArray) {
        if (![tmpDic isKindOfClass:[NSDictionary class]]) {
            continue;
        }
        NSObject *tmpObject = [self createObjectFromDictionary:tmpDic andClassName:className andPropertyArray:propertyArray andKeysArray:keysArray];
        
        [resArray addObject:tmpObject];
    }
    return resArray;
}

#pragma mark - 依据字典生成model
//生成Model数据类型的类，以存放数据
+(NSObject *)createObjectFromDictionary:(NSDictionary *)tmpDic andClassName:(NSString *)className andPropertyArray:(NSArray *)propertyArray andKeysArray:(NSArray *)keysArray
{
    if (!tmpDic || ![tmpDic isKindOfClass:[NSDictionary class]]) {
        return nil;
    }
    
    const char *cClassName = [className UTF8String];
    
    id theClass = objc_getClass(cClassName);
    
    NSObject *object = [[theClass alloc] init];
    
    for (int j=0; j< keysArray.count; j++) {
        NSString *tmpKey = [keysArray objectAtIndex:j];
        NSString *tmpValue = GlobalHandleValue([tmpDic valueForKey:tmpKey]);
        
        NSString *propertyName = [propertyArray objectAtIndex:j];
        
        SEL selector = NSSelectorFromString(propertyName);
        if ([object respondsToSelector:selector]) {
            [object setValue:tmpValue forKeyPath:propertyName];
        }
    }
    
    return object;
}

#pragma mark - 遍历数据为字典的情况，处理Null以及其它类型
+(void)filterDictionaryResultWithData:(NSMutableDictionary **)tmpdic
{
    for (NSString *tmpKey in (*tmpdic).allKeys) {
        id tmpValue = [(*tmpdic) valueForKey:tmpKey];
        if ([tmpValue isKindOfClass:[NSNull class]]) {
            tmpValue = @"";
        } else if ([tmpValue isKindOfClass:[NSDictionary class]]) {
            [self filterDictionaryResultWithData:&tmpValue];
        } else if ([tmpValue isKindOfClass:[NSArray class]]) {
            [self filterArrayResultWithData:&tmpValue];
        } else {
            tmpValue = [NSString stringWithFormat:@"%@", tmpValue];
        }
        [(*tmpdic) setObject:tmpValue forKey:tmpKey];
    }
}

#pragma mark - 遍历数据为数组的情况，处理Null以及其它类型
+(void)filterArrayResultWithData:(NSMutableArray **)tmpArray
{
    for (int i = 0; i < (*tmpArray).count; ++i) {
        id tmpValue = (*tmpArray)[i];
        if ([tmpValue isKindOfClass:[NSDictionary class]]) {
            [self filterDictionaryResultWithData:&tmpValue];
        } else if ([tmpValue isKindOfClass:[NSArray class]]) {
            [self filterArrayResultWithData:&tmpValue];
        }
        
        [(*tmpArray) replaceObjectAtIndex:i withObject:tmpValue];
    }
}

#pragma mark -- 默认解析方式，只返回最原始的经过json解析的数据
+(id)parseToDefaultValueWithData:(id)parseDataId
{
    //    id resId = [NSJSONSerialization JSONObjectWithData:parseDataId options:0 error:nil];
    if (!parseDataId) return nil;
    id resId = [NSJSONSerialization JSONObjectWithData:parseDataId options:NSJSONReadingMutableContainers error:nil];
    
    return resId;
}

#pragma mark -- 检查更新
+(void)checkversion:(void (^)(BOOL hasnewversion))result
{
    AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];
    sessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [sessionManager POST:[NSString stringWithFormat:@"http://itunes.apple.com/lookup?id=%@",APPID] parameters:nil progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //获取当前app信息
        NSDictionary * infoDic = [[NSBundle mainBundle] infoDictionary];
        NSString * currentVersion = [infoDic objectForKey:@"CFBundleShortVersionString"];//当前版本号
        //获取苹果商店最新的版本信息
        NSDictionary * rootDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSArray *infoArray = [rootDic objectForKey:@"results"];
        if (infoArray.count) {
            NSDictionary *releaseInfo = [infoArray objectAtIndex:0];
            NSString *lastVersion = [releaseInfo objectForKey:@"version"];//最新版本号
            if ([lastVersion floatValue] > [currentVersion floatValue]) {
                result(YES);
                return;
            }
        }
        result(NO);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        result(NO);
    }];
}

@end
